
const config = require('wy-Config');
const UI = require('wy-UI');
const querystring = require("querystring");
module.exports = {
    setOptions(option){
        option.token && (this.token = option.token);
        option.openid && (this.openid = option.openid);
    },
    post: function (router, params, cb) {
        var sendstr = JSON.stringify(params);
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.open("POST", config.httpRootUrl + router, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 300)) {
                try {
                    var data = JSON.parse(xhr.response);
                    if (!!cb && data.code === 200) {
                        cb(data.data);
                    } else {
                        UI.ToolTip({ message: data.msg });
                    }
                } catch (e) {
                    cc.error("err:" + e);
                }
            }
        };
        xhr.send(sendstr);
    },

    get: function (objname,router, params, cb) {
        router&& (params.router = router);
        this.openid&& (params.openid = this.openid);
        this.token&& (params.token = this.token);

        let url = `${config.httpRootUrl}${objname}?${querystring.stringify(params)}`;
        // cc.log('httpurl:',url);
        const xhr = cc.loader.getXMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
                cc.log('resp:'+xhr.response)
                var data = null;
                try {
                    data = JSON.parse(xhr.response);
                } catch (e) {
                    cb(e,null);
                    cc.error("err:" + e);
                    return;
                }
                if (!!cb && data.code === 200) {
                    cb(null,data.data);
                } else {
                    cb(data.code,data.data);
                    
                    cc.log('登陆失败！'+data);
                    UI.ToolTip({ message: data.msg });
                }
            } else {
                // cc.log("xhr.readyState,xhr.status", xhr.readyState, xhr.status);
            }
        }
        xhr.send();
        return xhr;
    }
}